﻿using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Windows.Forms.VisualStyles;
using System.Xml;
using System.Xml.Linq;

namespace HHSetupApp
{
    public partial class MainForm : Form
    {
        public MainForm()
        {



            InitializeComponent();

            this.Width = 638;
            this.gBox1.Location = new Point(0, 0);
        }

        private static string HHversion = "HHversion.json";
        private static string configFilename = "GenyeeUpdate.exe.config";

        private void button1_Click(object sender, EventArgs e)
        {

        }

        private void MainForm_Load(object sender, EventArgs e)
        {
            string exePath = Application.StartupPath + @"\GenyeeUpdate.exe.config";
            string filename = Application.StartupPath + @"\"+ HHversion;
            bool existone = false;
            #region 加载服务器的json配置文件
            if (File.Exists(filename))
            {
                existone = true;
                groupBox1.Visible = true;
                try
                {
                    FileStream fs = new FileStream(filename, FileMode.Open);
                    StreamReader sr = new StreamReader(fs, Encoding.UTF8);
                    string str = sr.ReadToEnd();
                    sr.Close();
                    fs.Close();
                    JsonConfig jsonConfig = JsonConvert.DeserializeObject<JsonConfig>(str);
                    this.textBox6.Text = jsonConfig.ReleaseUrl;
                    this.textBox5.Text = jsonConfig.ApplicationStart;
                    this.textBox4.Text = jsonConfig.ReleaseVersion;
                    this.richTextBox1.Text = jsonConfig.VersionDesc;
                }
                catch (Exception ex)
                {
                    MessageBox.Show("加载服务器json文件错误");
                }
            }
            #endregion



            #region 加载本地配置信息      
            //var dataFolder = Properties.Settings.Default.Path;

            ////Console.WriteLine(exeConfigPath);

            {
                //var folder = exeConfigPath.Substring(0, exeConfigPath.IndexOf("HHSetupApp.exe_")).Replace("\\HHSetupApp\\", "\\HHUpdateApp\\");
                //var result = ReadUserConfig(folder, "user.config", "LaunchAppVer");
               

               // var Appdata_LaunchAppVer = ReadUserConfig("user.config", "LaunchAppVer");

                var c = 0;
            }

            if (!existone)
            {

                gBox1.Visible = true;
                if (File.Exists(exePath))
                {

                    //var userName = System.Environment.UserName;
                    //C:\Users\Administrator\AppData\Local\HHUpdateApp\geafonMain.exe_Url_n0pmnsralu1cqkboqw3z3jblxw4z40uh\1.0.0.0

                    try
                    {
                        XmlDocument xDoc = new XmlDocument();
                        xDoc.Load(exePath);
                        XmlNodeList nodeList = xDoc.GetElementsByTagName("setting");
                        string LaunchAppName = "";
                        string ServerUpdateUrl = "";
                        string LaunchAppVer = "";
                        string MainAppName = "";
                        foreach (object obj in nodeList)
                        {
                            XmlNode item = (XmlNode)obj;
                            XmlAttributeCollection xmlAttributeCollection = item.Attributes;
                            if (xmlAttributeCollection != null)
                            {
                                XmlAttribute att = xmlAttributeCollection["name"];
                                if (att.Value == "LaunchAppName")
                                {
                                    LaunchAppName = item.SelectSingleNode("value").InnerText;

                                }
                                if (att.Value == "MainAppName")
                                {
                                    MainAppName = item.SelectSingleNode("value").InnerText;

                                }                               
                                if (att.Value == "ServerUpdateUrl")
                                {
                                    ServerUpdateUrl = item.SelectSingleNode("value").InnerText.Replace(HHversion,"") ;

                                }
                                if (att.Value == "LaunchAppVer")
                                {
                                    LaunchAppVer = item.SelectSingleNode("value").InnerText;

                                    var Appdata_LaunchAppVer = ReadUserConfig("user.config", "LaunchAppVer");

                                    if (Appdata_LaunchAppVer != "" && LaunchAppVer != Appdata_LaunchAppVer)
                                    {
                                        // WriteUserConfig( "user.config", "LaunchAppVer", LaunchAppVer);
                                        SetValue(configFilename,"LaunchAppVer", Appdata_LaunchAppVer);
                                        LaunchAppVer = Appdata_LaunchAppVer;
                                    }

                                }
                            }
                        }
                        this.textBox1.Text = ServerUpdateUrl;
                        this.textBox2.Text = LaunchAppName;
                        this.textBox3.Text = LaunchAppVer;
                        this.txtMainExe.Text = MainAppName;
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show("加载本地配置文件错误");
                    }
                }
            }
            #endregion

        }
        static string exeConfigPath = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.PerUserRoamingAndLocal).FilePath;
        static string folder = exeConfigPath.Substring(0, exeConfigPath.IndexOf("HHSetupApp.exe_")).Replace("\\HHSetupApp\\", "\\HHUpdateApp\\");
        public static string ReadUserConfig(string fileName, string key)
        {
            try
            {
               
                string directoryPath = folder;
                Console.WriteLine("folder:" + folder);
                // 遍历文件夹，查找配置文件  
                foreach (string filePath in Directory.GetFiles(directoryPath, fileName, SearchOption.AllDirectories))
                {
                    if (!ExistCurrentExe(filePath))
                    {
                        continue;
                    }

                    string LaunchAppPath= ReadLaunchAppVer(filePath, "LaunchAppPath");
                    if (Application.StartupPath != LaunchAppPath) {
                        continue;
                    }


                    // 读取 LaunchAppVer 的值  
                    string launchAppVer = ReadLaunchAppVer(filePath, key);
                    Console.WriteLine($"当前 LaunchAppVer: {launchAppVer}");

                    return launchAppVer;

                    //// 修改 LaunchAppVer 的值  
                    //string newVersion = "2.0.0.0"; // 你想修改的新版本号  
                    //UpdateLaunchAppVer(filePath, newVersion);
                    //Console.WriteLine($"已将 LaunchAppVer 更新为: {newVersion}");
                }
            }
            catch { }
            return "";
        }

        static bool ExistCurrentExe(string filePath) {
            string runfolder = System.Environment.CurrentDirectory;
            List<string> fileNames = new List<string>();

            try
            {
                // 获取指定目录下的所有文件  
                string[] files = Directory.GetFiles(runfolder);
                // 将文件名添加到列表中  
                foreach (string file in files)
                {
                    var filename = Path.GetFileName(file);
                    if (filename.EndsWith(".exe"))
                    { fileNames.Add(filename); }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"发生错误: {ex.Message}");
            }
            bool existexe = false;
            foreach (var item in fileNames)
            {
                if (filePath.IndexOf(item) > 0)
                {
                    existexe = true; break;
                }
            }
          
            return existexe;
        }



        static string ReadLaunchAppVer(string filePath, string key)
        {
            XDocument xdoc = XDocument.Load(filePath);
            var launchAppVer = xdoc.Descendants("setting")
                .FirstOrDefault(s => (string)s.Attribute("name") == key)
                ?.Element("value")?.Value;

            return launchAppVer ?? "";
        }


        public static string WriteUserConfig(string fileName, string key, string value,bool nocheckpath)
        {
            try
            {
                bool exists = false;

                string directoryPath = folder;
                // 遍历文件夹，查找配置文件  
                foreach (string filePath in Directory.GetFiles(directoryPath, fileName, SearchOption.AllDirectories))
                {
                    if (!ExistCurrentExe(filePath))
                    {
                        continue;
                    }

                    string LaunchAppPath = ReadLaunchAppVer(filePath, "LaunchAppPath");
                    if (Application.StartupPath != LaunchAppPath && nocheckpath)
                    {
                        continue;
                    }
                    Console.WriteLine("LaunchAppPath" + LaunchAppPath);
                    if (!nocheckpath && !string.IsNullOrEmpty(LaunchAppPath)) {
                        continue;
                    }


                    exists = true;
                    //// 修改 LaunchAppVer 的值  
                    //string newVersion = "2.0.0.0"; // 你想修改的新版本号  
                    UpdateLaunchAppVer(filePath, key, value);
                    //Console.WriteLine($"已将 LaunchAppVer 更新为: {newVersion}");
                }

                if (!exists && nocheckpath) {
                    WriteUserConfig(fileName, key, value, false);
                }


            }
            catch { }
            return "";
        }

        static void UpdateLaunchAppVer(string filePath, string key, string newVersion)
        {
            XDocument xdoc = XDocument.Load(filePath);
            var setting = xdoc.Descendants("setting")
                .FirstOrDefault(s => (string)s.Attribute("name") == key);

            if (setting != null)
            {
                setting.Element("value").Value = newVersion;
                xdoc.Save(filePath); // 保存更改  
            }
            else
            {
                Console.WriteLine("未找到 LaunchAppVer 设置以进行更新");
            }
        }

        public static void SetValue(string filename, string appKey, string appValue)
        {
            string exePath = Application.StartupPath + "/" +filename;
            XmlDocument xDoc = new XmlDocument();
            xDoc.Load(exePath);
            XmlNodeList nodeList = xDoc.GetElementsByTagName("setting");
            foreach (object obj in nodeList)
            {
                XmlNode item = (XmlNode)obj;
                XmlAttributeCollection xmlAttributeCollection = item.Attributes;
                if (xmlAttributeCollection != null)
                {
                    XmlAttribute att = xmlAttributeCollection["name"];
                    if (att.Value == appKey)
                    {
                        item.SelectSingleNode("value").InnerText = appValue;
                        break;
                    }
                }
            }
            xDoc.Save(exePath);

            //if (exePath.Contains(".exe"))
            //{
            //    exePath = exePath + ".config";//appName.dat.config
            //    if (File.Exists(exePath))
            //    {
            //        xDoc.Save(exePath);
            //    }
            //}



            //if (exePath.Contains(".exe"))
            //{
            //    exePath = exePath.Replace(".exe", ".dat") + ".config";//appName.dat.config
            //    if (File.Exists(exePath))
            //    {
            //        xDoc.Save(exePath);
            //    }
            //}
            //else
            //{
            //    exePath = exePath.Replace(".dat", ".exe") + ".config";
            //    if (File.Exists(exePath))
            //    {
            //        xDoc.Save(exePath);
            //    }
            //}

            //读取本地配置
            //C:\Users\Administrator\AppData\Local\HHUpdateApp


        }
        public class JsonConfig
        {
            public string ApplicationStart { get; set; }
            public string ReleaseUrl { get; set; }
            public string ReleaseVersion { get; set; }
            public string VersionDesc { get; set; }
            public string IgnoreFile { get; set; }

            public string FileType { get; set; }
        }



        private void btnServerConfig_Click(object sender, EventArgs e)
        {
            string filename = Application.StartupPath + @"\"+ HHversion;
            FileStream fsread = new FileStream(filename, FileMode.Open);
            StreamReader srread = new StreamReader(fsread, Encoding.UTF8);
            string str = srread.ReadToEnd();
            srread.Close();
            fsread.Close();
            JsonConfig jsonConfig = JsonConvert.DeserializeObject<JsonConfig>(str);
            jsonConfig.ReleaseUrl = this.textBox6.Text;
            jsonConfig.ApplicationStart = this.textBox5.Text;
            jsonConfig.ReleaseVersion = this.textBox4.Text;
            jsonConfig.VersionDesc = this.richTextBox1.Text;
            jsonConfig.FileType = jsonConfig.ReleaseUrl.Substring(jsonConfig.ReleaseUrl.LastIndexOf("."));

            FileStream fs;
            StreamWriter sw;
            try
            {
                File.Delete(filename);
                //保存协议信息
                fs = new FileStream(filename, FileMode.Create);
                sw = new StreamWriter(fs, Encoding.UTF8);
                sw.Write(JsonConvert.SerializeObject(jsonConfig));
                sw.Close();
                fs.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
            MessageBox.Show("保存成功");

        }

        private void btnClientConfig_Click(object sender, EventArgs e)
        {
            string ServerUpdateUrl = this.textBox1.Text;
            if (!ServerUpdateUrl.EndsWith(HHversion)) {
                if (ServerUpdateUrl.EndsWith("/")) {
                    ServerUpdateUrl = ServerUpdateUrl + HHversion;
                }
                else {
                    ServerUpdateUrl = ServerUpdateUrl + "/" + HHversion;
                }
            }

            SetValue(configFilename, "MainAppName", this.txtMainExe.Text);
            SetValue(configFilename, "ServerUpdateUrl", ServerUpdateUrl);
            SetValue(configFilename, "LaunchAppName", this.textBox2.Text);
            SetValue(configFilename, "LaunchAppVer", this.textBox3.Text);

            if (!string.IsNullOrEmpty(this.txtMainExe.Text))
            {
                string txtMainExeText = this.txtMainExe.Text;
                if (!txtMainExeText.ToLower().EndsWith(".exe")) {
                    txtMainExeText += ".exe";
                }
                txtMainExeText += ".config";
                SetValue(txtMainExeText, "ServerUpdateUrl", ServerUpdateUrl);
                SetValue(txtMainExeText, "LaunchAppName", this.textBox2.Text);
                SetValue(txtMainExeText, "LaunchAppVer", this.textBox3.Text);
            }

            WriteUserConfig("user.config", "LaunchAppVer", this.textBox3.Text,true);
            WriteUserConfig("user.config", "LaunchAppPath", Application.StartupPath, true);

            //Properties.Settings.Default.LaunchAppVer = this.textBox3.Text;
            //Properties.Settings.Default.Save();

            MessageBox.Show("更新成功");
        }
    }
}
